import React from 'react';
import _ from 'lodash';
import { ISubmitEvent } from '../../sys.dom';
import { Form, FormFields } from '../../components/forms';
import { SearchButton } from '../../components/buttons';
import { CheckBoxGroup } from '../../components/check-box';
import { SearchBox, DateRangeGroup, NumberRangeGroup } from '../../components/text-box';
import { IBookQueryAllCriteria, BookCategory, BookCategoryOptions } from './books.api';

export interface IBookQueryPanelProps {
    criteria: IBookQueryAllCriteria,
    onSubmit: (evt: ISubmitEvent<IBookQueryAllCriteria>) => void;
}

export class BookQueryPanel extends React.Component<IBookQueryPanelProps> {
    private categoriesRef: React.RefObject<CheckBoxGroup> = React.createRef();
    private keyRef: React.RefObject<SearchBox> = React.createRef();
    private priceRangeRef: React.RefObject<NumberRangeGroup> = React.createRef();
    private pubDateRangeRef: React.RefObject<DateRangeGroup> = React.createRef();

    private handleSubmit = (evt: React.MouseEvent<HTMLButtonElement>): void => {
        const [minPrice, maxPrice] = this.priceRangeRef.current.getValue();
        const [minPubDate, maxPubDate] = this.pubDateRangeRef.current.getValue();

        this.props.onSubmit({
            value: {
                categories: this.categoriesRef.current.getValue().map(sv => parseInt(sv, 10) as BookCategory),
                key: _.trim(this.keyRef.current.getValue()),
                minPrice,
                maxPrice,
                minPubDate,
                maxPubDate,
            }
        });
    }

    shouldComponetUpdate = (nextProps: IBookQueryPanelProps) => !_.isEqual(nextProps.criteria, this.props.criteria);

    render = (): JSX.Element => {
        const { categories, key, minPrice, maxPrice, minPubDate, maxPubDate } = this.props.criteria;
        return <Form>
            <FormFields>
                <CheckBoxGroup className="six wide field" labelText="类别：" options={BookCategoryOptions} checked={categories} ref={this.categoriesRef} />
                <SearchBox className="six wide field" labelText="关键字：" placeholder="关键字" defaultValue={key} autoFocus={true} ref={this.keyRef} />
            </FormFields>
            <FormFields>
                <NumberRangeGroup className="six wide field" labelText="价格：" fractionDigits={2}
                    minPlaceholder="最低价格" maxPlaceholder="最高价格"
                    minNumberValue={minPrice} maxNumberValue={maxPrice} ref={this.priceRangeRef} />
                <DateRangeGroup className="six wide field" labelText="发布日期："
                    minPlaceholder="最早发布日期" maxPlaceholder="最晚发布日期"
                    minDateValue={minPubDate} maxDateValue={maxPubDate} ref={this.pubDateRangeRef} />
                <SearchButton className="ui primary button" onClick={this.handleSubmit} />
            </FormFields>
        </Form>;
    };
}